﻿using System;
using System.Diagnostics.Contracts;
using System.Drawing;

namespace OpenWaves.ImageTransformations
{
    internal class GdiTransformationParameters : IImage
    {
        private int width;
        public int Width
        {
            get { return this.width; }
        }

        private int height;
        public int Height
        {
            get { return this.height; }
        }

        private Rectangle sourceRectangle;
        public Rectangle SourceRectangle
        {
            get { return this.sourceRectangle; }
        }

        public GdiTransformationParameters(int width, int height)
        {
            Contract.Requires<ArgumentOutOfRangeException>(width > 0);
            Contract.Requires<ArgumentOutOfRangeException>(height > 0);

            this.sourceRectangle = new Rectangle(0, 0, width, height);
            this.width = width;
            this.height = height;
        }

        public void Scale(int newWidth, int newHeight)
        {
            this.width = newWidth;
            this.height = newHeight;
        }

        public void Crop(int left, int top, int newWidth, int newHeight)
        {
            var horizontalScale = (double)this.Width / this.SourceRectangle.Width;
            var verticalScale = (double)this.Height / this.SourceRectangle.Height;

            this.width = newWidth;
            this.height = newHeight;

            var newSourceRectangle = new Rectangle(
                (int)(this.SourceRectangle.X + left / horizontalScale),
                (int)(this.SourceRectangle.Y + top / verticalScale),
                (int)(this.Width / horizontalScale),
                (int)(this.Height / verticalScale));

            Contract.Assert(this.sourceRectangle.Contains(newSourceRectangle));

            this.sourceRectangle = newSourceRectangle;
        }
    }
}